import { RouteRecordRaw } from "vue-router";

/** 路由过滤成菜单 */
export function filterRoutesToMenus(routes: RouteRecordRaw[]) {
  const menus: App.Menu[] = [];

  routes.forEach((route: RouteRecordRaw) => {
    const menuItem: App.Menu = {
      path: route.path,
      title: route.meta?.title || "",
      icon: route.meta?.icon,
    };
    if (route.children && route.children.length > 0) {
      menuItem.children = filterRoutesToMenus(route.children);
    }
    if (!route.meta?.isHide) menus.push(menuItem);
  });
  return menus;
}

const Layout = () => import("@/layout/index.vue");
const ParentView = () => import("@/layout/components/ParentView/index.vue");
/** 处理后端路由字符串，转换成组件对象 **/
export function filterAsyncRouter(asyncRouterMap, type = false) {
  return asyncRouterMap.filter((route) => {
    // children的path拼接。若后端返回的path为完整path，则无需处理（type为false，默认无需处理)
    if (type && route.children) {
      route.children = filterChildren(route.children);
    }
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === "Layout") {
        route.component = Layout;
      } else if (route.component === "ParentView") {
        route.component = ParentView;
      } else {
        route.component = loadView(route.component);
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, type);
    } else {
      delete route["children"];
      delete route["redirect"];
    }
    return true;
  });
}

/** 拼接子路由path **/
function filterChildren(
  childrenMap,
  lastRouter: boolean | RouteRecordRaw = false
) {
  let children = [];
  childrenMap.forEach((el) => {
    if (el.children && el.children.length) {
      if (el.component === "ParentView" && !lastRouter) {
        el.children.forEach((c) => {
          c.path = el.path + "/" + c.path;
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c));
            return;
          }
          children.push(c);
        });
        return;
      }
    }
    if (lastRouter) {
      if ("path" in lastRouter) {
        el.path = lastRouter.path + "/" + el.path;
      }
      if (el.children && el.children.length) {
        children = children.concat(filterChildren(el.children, el));
        return;
      }
    }
    children = children.concat(el);
  });
  return children;
}

// 匹配view里面所有的.vue文件
const modules: Record<string, { [key: string]: any }> = import.meta.glob(
  "@/views/**/*.vue",
  {
    eager: true,
  }
);
export const loadView = (view) => {
  let res;
  for (const path in modules) {
    const dir = path.split("views")[1].split(".vue")[0];
    if (dir === view) {
      res = modules[path].default;
    }
  }
  return res;
};
